import { Coupon, CouponService } from "@mallfoundry/marketing/coupon"
import { PageList } from "@mallfoundry/shared/data"
import { useEffect, useState } from "react"

interface UseCouponsOptions {
  page?: number | string
  limit?: number | string
  storeId?: string
  name?: string
  types?: string
  statuses?: string
  timestamp?: string
}

export function useCoupons(options: UseCouponsOptions) {
  const { page, limit, storeId, name, types, statuses } = options
  const [loading, setLoading] = useState(false)
  const [pageCoupons, setPageCoupons] = useState(PageList.empty<Coupon>())
  useEffect(() => {
    setLoading(true)
    CouponService.getCoupons(CouponService
      .createCouponQuery().toBuilder()
      .page(page).limit(limit)
      .storeId(storeId).name(name)
      .types(types).statuses(statuses)
      .build())
      .then(setPageCoupons)
      .finally(() => setLoading(false))
  }, [page, limit, storeId, name, types, statuses])

  return {
    loading,
    ...pageCoupons,
  }
}
